const express = require('express');
const router = express.Router();
const { getToken } = require('../token/token');
const executeQuery = require('../MySQL/connect');

// 更新学生信息的路由处理程序
router.put('/:id', async (req, res) => {
    const tokenResult = getToken(req.headers.authorization);
    if (!tokenResult.boolean) {
        return res.status(405).send(tokenResult.msg);
    }

    if(!tokenResult.isAdmin){
      return res.status(401).send('你不是管理员，无法修改');
    }
    
    const studentId = req.params.id;
    const updatedStudent = req.body;

    try {
        // 将日期字段格式化为 MySQL 可接受的格式
        const formattedEnrollmenTime = new Date(updatedStudent.EnrollmenTime).toISOString().slice(0, 19).replace('T', ' ');

        // 执行更新学生信息的 SQL 查询
        const updateQuery = `UPDATE Students
                             SET name = ?, sex = ?, age = ?, College = ?,
                                 class = ?, specialized = ?, guardian = ?,
                                 phone = ?, address = ?, identityCard = ?,
                                 EnrollmenTime = ?, remark = ?
                             WHERE id = ?`;

        const values = [
            updatedStudent.name,
            updatedStudent.sex,
            updatedStudent.age,
            updatedStudent.College,
            updatedStudent.class,
            updatedStudent.specialized,
            updatedStudent.guardian,
            updatedStudent.phone,
            updatedStudent.address,
            updatedStudent.identityCard,
            formattedEnrollmenTime,  // 使用格式化后的日期
            updatedStudent.remark,
            studentId
        ];

        await executeQuery(updateQuery, values);

        res.status(200).send({ message: 'Student information updated successfully' });
    } catch (error) {
        console.error(error);
        res.status(500).send({ message: 'Internal Server Error' });
    }
});

module.exports = router;
